<?php

use \esp\core\Dispatcher;
use \esp\library\gd\Image;
use \esp\core\Config;
use \esp\plugs\Example;
use \esp\core\Mistake;

final class Bootstrap
{

    //判断当前访问是不是一个缩略图格式，若是，直接创建且后面不再执行
    public function _initThumbs(Dispatcher $dispatcher)
    {
        if (_CLI or !getenv('REQUEST_FILENAME')) return;
        $pattern = '/^\/(.+?)\.(jpg|gif|png|bmp|jpeg)\_(\d{1,4})(x|v|z)(\d{1,4})\.\2(?:[\?\#].*)?$/i';
        if (preg_match($pattern, getenv('REQUEST_URI'))) {
            exit(Image::thumbs());
        }
    }

    public function _initDebug(Dispatcher $dispatcher)
    {
        Config::format('database');

        /**
         * 启用Error
         */
        $eConf = Config::system('frame.error');
        $path = $eConf['path'] ?? 'error';
        new Mistake($dispatcher, intval($eConf['display'] ?? 1), function ($array) use ($path, $dispatcher) {
            $info = [];
            $info['time'] = date('Y-m-d H:i:s');
            $info['host'] = getenv('HTTP_HOST');
            $info['url'] = _URI;
            $info['ip'] = getenv('REMOTE_ADDR');
            $info['agent'] = getenv('HTTP_USER_AGENT');
            $info['referer'] = getenv("HTTP_REFERER");
            if (!is_null($dispatcher->debug)) {
                $info['debug'] = $dispatcher->debug->error();
                $file = urlencode($info['debug']);
                $info['debug'] = "<a href='/tools/debug/{$file}'>{$info['debug']}</a>";
            }
            save_file(root($path) . date("/ERR_ymdHis_") . mt_rand() . '.txt', print_r($info, true) . "\n\n" . print_r($array, true));
        });

    }

    public function _initRegPlugs(Dispatcher $dispatcher)
    {
        $dispatcher->setPlugin(new Example());
    }

}